# coding: utf8
__author__ = 'Tony'

import datetime
import random
import logging
from umeng_tool.analyse.models import UserKeepStatistic, VirtualUser, KeyTimeNode
from umeng_tool.analyse.strategy.user_login_task import task as login_scheduler


run_log = logging.getLogger('run')


class Task(object):
    """
    用户留存量任务
    """
    USER_KEEP_PROBABILITY = [0.20, 0.10, 0.5, 0.3, 0.3]  # 5天内留存趋率趋势

    def __init__(self, login_scheduler):
        self.login_scheduler = login_scheduler

    def runner(self):
        """
        用户留存任务运行器
        :return: 留存用户样本数
        """
        today = datetime.date.today()
        used_user_ids = []
        used_users = []

        KeyTimeNode.objects.all().delete()

        for i in range(5):
            create_date = today - datetime.timedelta(days=i)
            keep_percent = self.USER_KEEP_PROBABILITY[i] + random.uniform(-0.2, 0.2)
            user_keep = UserKeepStatistic.simulate_keep_users(create_date, keep_percent)
            for u in user_keep:
                used_user_ids.append(u.id)
                used_users.append(u)
        random_user_keep_count = int(VirtualUser.objects.all().count() * 0.2) - len(used_user_ids)
        if random_user_keep_count > 0:
            other_user = VirtualUser.objects.exclude(id__in=used_user_ids)
            random_user_keep = random.sample(other_user, random_user_keep_count)
            used_users += random_user_keep

        for u in used_users:
            KeyTimeNode.make_key_times(u)
            u.make_next_online()

        run_log.info('留存用户数：%s' % len(used_users))
        return len(used_users)


task = Task(login_scheduler)
